package me.heyclock.hl.recordwriter.app;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.ui.RecognizerDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.heyclock.hl.recordwriter.R;
import me.heyclock.hl.recordwriter.activity.LoginActivity;
import me.heyclock.hl.recordwriter.adapter.HomeFunctionAdapter;
import me.heyclock.hl.recordwriter.adapter.OnItemClickListener;
import me.heyclock.hl.recordwriter.bean.HomeFunctionBean;
import me.heyclock.hl.recordwriter.robot.ActivityStack;
import me.heyclock.hl.recordwriter.robot.MyRecognizerDialogLis;
import me.heyclock.hl.recordwriter.robot.MySynthesizerListener;
import me.heyclock.hl.recordwriter.robot.SpeechTool;
import me.heyclock.hl.recordwriter.robot.StateMachine;
import me.heyclock.hl.recordwriter.tools.AppUtils;
import me.heyclock.hl.recordwriter.tools.HC_Screen;
import me.heyclock.hl.recordwriter.tools.MediaPlayTool;
import me.heyclock.hl.recordwriter.tools.PermissionTool;
import me.heyclock.hl.recordwriter.tools.SystemUtils;
import me.heyclock.hl.recordwriter.tools.TimeUtils;
import me.heyclock.hl.recordwriter.ui.MarqueeTextView;
import me.heyclock.hl.recordwriter.ui.WinManager;

public class HomeActivity extends BaseAppCompatActivity {

    //    // Used to load the 'native-lib' library on application startup.
    //    static {
    //        System.loadLibrary("native-lib");
    //    }

    //    /**
    //     * A native method that is implemented by the 'native-lib' native library,
    //     * which is packaged with this application.
    //     */
    //    public native String stringFromJNI();

    @BindView(R.id.ah_recorde_nowTv)
    public MarqueeTextView recorde_nowTv;
    @BindView(R.id.ah_functionRv)
    public RecyclerView functionRv;

    /**
     * @讯飞
     */
    private RecognizerDialog recognizerDialog = null;
    private String audioPath = AppUtils.RW_AUDIO_TEMP_PATH + "/iat.wav";
    private String audioText = "";
    private SpeechSynthesizer mTts = null;
    private MySynthesizerListener mSynListener = null;

    private List<HomeFunctionBean> homeFunctionBeanList = new ArrayList<>();
    private HomeFunctionAdapter homeFunctionAdapter;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            recorde_nowTv.setText((String) msg.obj);
            switch (msg.what) {
                case -1:
                    /**
                     * 添加语音悬浮按钮
                     */
                    WinManager.add(HomeActivity.this, R.layout.view_audio_surfaceview,
                            (int) (300 * HC_Screen.ratio_width), (int) (300 * HC_Screen.ratio_width),
                            HC_Screen.SCREEN_WIDTH / 2 - (int) (150 * HC_Screen.ratio_width),
                            HC_Screen.SCREEN_HEIGHT - (int) (300 * HC_Screen.ratio_width), new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (null != recognizerDialog &&
                                            recognizerDialog.isShowing()) {
                                        return;
                                    }
                                    ///< 录音权限检查
                                    if (!PermissionTool.checkPermissionRecorde(HomeActivity.this)) {
                                        return;
                                    }
                                    ///< 外卡读写权限判断
                                    if (!PermissionTool.checkPermissionAll(HomeActivity.this)) {
                                        return;
                                    }

                                    ///< 暂停一下
                                    MediaPlayTool.pause(HomeActivity.class.getName());

                                    ///< 每次录音以时间戳作为音频名称
                                    long curTime = TimeUtils.getCurrentTime();
                                    audioPath = AppUtils.RW_AUDIO_TEMP_PATH + "/" + curTime + ".wav";
                                    audioText = "";
                                    recognizerDialog.setParameter(SpeechConstant.ASR_AUDIO_PATH,
                                            audioPath);
                                    recognizerDialog.show();
                                }
                            });
                    break;
                case -2:
                    ///< 暂停一下
                    MediaPlayTool.pause(HomeActivity.class.getName());

                    ///< 每次录音以时间戳作为音频名称
                    long curTime = TimeUtils.getCurrentTime();
                    audioPath = AppUtils.RW_AUDIO_TEMP_PATH + "/" + curTime + ".wav";
                    audioText = "";
                    recognizerDialog.setParameter(SpeechConstant.ASR_AUDIO_PATH,
                            audioPath);
                    if (recognizerDialog.isShowing()){
                        recognizerDialog.dismiss();
                    }
                    recognizerDialog.show();
                    break;
                case 0:
                    ///< 对话开启
                    StateMachine.getCommand((String) msg.obj, new StateMachine.ReBackListenner() {
                        @Override
                        public void reply(StateMachine.RE_COMMAND_TYPE re_command_type, Object msg, Object activity) {
                            if (re_command_type == StateMachine.RE_COMMAND_TYPE.HELLO) {
                                ///< 设置声音播放参数，播放完成回调可以根据类型判断回调完成做什么？
                                mTts.setParameter("type", "hello");
                                mTts.startSpeaking((String) msg, mSynListener);
                            } else if (re_command_type == StateMachine.RE_COMMAND_TYPE.WHERE ||
                                    re_command_type == StateMachine.RE_COMMAND_TYPE.UNKNOW) {
                                mTts.setParameter("type", "where_unkonw");
                                mTts.startSpeaking((String) msg, mSynListener);
                            }
                            else if (re_command_type == StateMachine.RE_COMMAND_TYPE.JUMP) {
                                Intent intent = new Intent(HomeActivity.this, (Class)activity);
                                startActivity(intent);
                            }
                            else if (re_command_type == StateMachine.RE_COMMAND_TYPE.CLOSE) {
                                ((Activity)activity).finish();
                            }
                        }
                    });
                default:
                    break;
            }
        }
    };
    /**
     * UI消息处理 - 封装的Handler有问题
     */
    //private BaseHandler handler = new BaseHandler<>

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);
        ActivityStack.addActivity(HomeActivity.this);
        initView();
        initService();
    }

    /**
     * 初始化界面
     */
    private void initView() {
        homeFunctionBeanList.add(new HomeFunctionBean(0, "Mine",
                R.drawable.home_fun_mine, -1, LoginActivity.class, HC_Screen.SCREEN_WIDTH, HC_Screen.SCREEN_WIDTH / 2, getResources().getColor(R.color.blue_pull)));
        homeFunctionBeanList.add(new HomeFunctionBean(1, "NULL",
                R.mipmap.ic_launcher, -1, LoginActivity.class, -10000, -10000, R.color.me_white));
        homeFunctionBeanList.add(new HomeFunctionBean(1, "History",
                R.drawable.home_fun_history, -1, LoginActivity.class, HC_Screen.SCREEN_WIDTH / 2, HC_Screen.SCREEN_WIDTH / 2, getResources().getColor(R.color.colorPrimary)));
        homeFunctionBeanList.add(new HomeFunctionBean(2, "Wait",
                R.drawable.home_fun_wait, -1, LoginActivity.class, HC_Screen.SCREEN_WIDTH / 2, HC_Screen.SCREEN_WIDTH / 2, getResources().getColor(R.color.colorAccent)));
        homeFunctionAdapter = new HomeFunctionAdapter(this, homeFunctionBeanList);
        homeFunctionAdapter.setOnItemClickListener(new OnItemClickListener<HomeFunctionBean>() {
            @Override
            public void onClick(View v, HomeFunctionBean data) {
                Intent intent = new Intent(HomeActivity.this, data.getFunctionGoView());
                startActivity(intent);
            }

            @Override
            public void onClick(View v, int position) {

            }
        });
        functionRv.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        functionRv.setAdapter(homeFunctionAdapter);
        {
            ///< 讯飞识别弹窗
            recognizerDialog = SpeechTool.getRecognizerDialog(this, new MyRecognizerDialogLis(this, new MyRecognizerDialogLis.RecDialCallBack() {
                @Override
                public void replyMsg(String msg) {
                    ///< 录音显示在抬头
                    Message message = new Message();
                    message.what = 0;
                    audioText = msg;
                    message.obj = msg;
                    mHandler.sendMessage(message);

                    File file = new File(audioPath);
                    if (file.exists()) {
                        ///< TODO 上传音频和文本到服务器
                        ///< TODO 成功了则刷新列表界面【采用插入或者刷新的方式】
                        ///< TODO 失败了，则暂时存到本地，然后显示同步
                    }
                }
            }), new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    ///< 继续播放
                    MediaPlayTool.play(HomeActivity.class.getName());
                }
            });
            mTts = SpeechTool.getSpeechSynthesizer(this);
            mSynListener = new MySynthesizerListener(this, new MySynthesizerListener.ProcessBack() {
                @Override
                public void onComplete() {
                    if (mTts.getParameter("type").equals("hello")){
                        ///< 用完立即清空，避免无效判断
                        mTts.setParameter("type", "");
                        Message message = new Message();
                        message.what = -2;
                        message.obj = "read go";
                        mHandler.sendMessageDelayed(message, 1000);
                    }
                }
            });
        }

        ///< 检查悬浮窗权限成功后添加悬浮窗按钮
        if (PermissionTool.checkOverLays(this)) {
            Message message = new Message();
            message.what = -1;
            message.obj = "read go";
            mHandler.sendMessageDelayed(message, 2000);
        }

        ///< @hl(目前只有一套资源，且不想采用多套dimens, so...)
        HC_Screen.setConstraintLayoutWH(recorde_nowTv, 800, -10000);

        ///< 来点音乐
        MediaPlayTool.init(HomeActivity.class.getName(), this, R.raw.bgm);
        //MediaPlayTool.play(HomeActivity.class.getName());
    }

    /**
     * 初始化服务
     */
    private void initService() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (requestCode == 10) {
                if (Settings.canDrawOverlays(HomeActivity.this)) {
                    Message message = new Message();
                    message.what = -1;
                    message.obj = "ready go";
                    ///< 延迟加载录音按按钮
                    mHandler.sendMessageDelayed(message, 1000);
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != recognizerDialog) {
            if (recognizerDialog.isShowing()) {
                recognizerDialog.dismiss();
            }
            recognizerDialog = null;
        }
        MediaPlayTool.release(HomeActivity.class.getName());
        WinManager.removeView(HomeActivity.this);
        ActivityStack.removeActivty();
    }
}
